package com.github.tetrisgame.utils;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.lang.ref.WeakReference;

public class PermissionUtils {
    public static final PermissionUtils sharedInstance = new PermissionUtils();
    private WeakReference<AppCompatActivity> weakActivity;

    private ActivityResultLauncher<String> launcher;
    private OnRequestPermissionListener mListener;


    private PermissionUtils() {
    }

    public void init(AppCompatActivity activity, String message) {
        weakActivity = new WeakReference<>(activity);
        launcher = activity.registerForActivityResult(new ActivityResultContracts.RequestPermission(), granted -> {
            if (granted) {

            } else {
                showDialog(message);
            }
            if (mListener != null) {
                mListener.OnRequestPermission(granted);
            }
        });

    }

    public void showDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(weakActivity.get());
        builder.setTitle("提示");
        builder.setMessage(message);
        builder.setPositiveButton("立即设置", ((dialog, which) -> {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + weakActivity.get().getPackageName()));
            weakActivity.get().startActivity(intent);
        }));
        builder.setNegativeButton("取消", (dialog, which) -> {
            builder.create().dismiss();
        });
        builder.create().show();
    }


    public boolean checkPermission(String permission) {
        return weakActivity.get().checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }

    public void requestPermission(String permission, OnRequestPermissionListener listener) {
        this.mListener = listener;
        launcher.launch(permission);
    }


    public interface OnRequestPermissionListener {
        void OnRequestPermission(boolean granted);
    }


}
